import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;


public abstract class MailService {

  String host;
  String password;
  String user;
  BufferedReader reader;
  BufferedWriter writer;
  SSLSocket socket;
  // boolean isConnected;
  int port;

  public void connect(String host, int port) throws IOException {
    socket =
        (SSLSocket) ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(host, port);
    reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    readBufferLine();
    // isConnected = reader.readLine().contains("OK");
  }

  public void sendCommand(String cmd) {
    // System.out.println("cmd: " + cmd);
    try {
      writer.write(cmd + "\r\n");
      writer.flush();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public void disconnect() throws IOException {
    socket.close();
    // isConnected = false;
    reader = null;
    writer = null;
    // System.out.println("Connection closed");
  }

  public String readBufferLine() {
    String line = "";
    try {
      line = reader.readLine();
    } catch (IOException e) {
      e.printStackTrace();
    }
    // System.out.println(line);
    return line;
  }

  public String readBufferLines(String endPattern) {
    String line = "";
    StringBuilder response = new StringBuilder();
    try {
      while (!line.matches(endPattern)) {
        response.append("\n");
        line = reader.readLine();
        response.append(line);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return response.toString();
  }
}
